<template>
  <Layout.Content
    v-loading="state?.loading || false"
    class="pdf-view pdf-view-wrap overflow-auto"
    v-bind="$attrs"
  >
    <div class="pdf-view-canvas relative flex flex-col items-center pt-5">
      <canvas v-for="(_, index) in state?.pdfPages" :ref="(ref) => register(ref, index)" />

      <slot />
    </div>
  </Layout.Content>

  <PDFViewFooter
    v-if="props.isFooter !== false"
    simple
    :current="state.currentPage"
    :defaultPageSize="1"
    :total="state.pdfPages"
    @change="(e) => contractClass?.renderPage(contractCanvas?.[0], e || 1)"
  />
</template>

<script name="PDFView" lang="ts" setup>
  import { unref, watch } from 'vue';
  import { useContractCanvas } from '../_core/useContractCanvas';
  import { Layout } from 'ant-design-vue';
  import { useRoute } from 'vue-router';
  import PDFViewFooter from './components/PDFViewFooter.vue';
  import { usePDFViewContext } from './hooks/usePDFViewContext';
  import { propTypes } from '@/utils/propTypes';

  defineOptions({
    name: 'PDFView',
  });

  const props = defineProps({
    file: String,
    isFooter: propTypes.bool.def(false),
    isPagination: propTypes.bool.def(true),
  });

  const route = useRoute();
  const [register, contractClass] = useContractCanvas();
  const contractCtx = usePDFViewContext();
  const contractCanvas = contractClass.contractCanvas;
  const { state } = unref(contractClass);

  watch(
    () => [route.query, props.file, contractCtx.contractPdfInfo.value] as const,
    async ([query, file, data = {}]) => {
      await contractClass.loadFile(file || query?.['file'] || data?.address);
    },
    { immediate: true },
  );

  watch(
    () => contractClass,
    async (val) => {
      contractCtx.contractClass = val;
    },
    { immediate: true },
  );

  watch(
    contractClass.contractCanvas,
    (val) => {
      const dom = val;
      if (!dom.length) return;
      if (props.isPagination === true) {
        contractClass.renderPage(dom[0], 1);
      } else if (dom.length) {
        if (dom.length !== state.pdfPages) return;
        dom.forEach((el, index) => {
          contractClass.renderPage(el, index + 1);
        });
      }
    },
    {
      immediate: true,
      deep: true,
    },
  );
</script>

<style lang="less" scoped>
  .pdf-view-wrap {
    padding-top: @header-height;
    height: 100vh;
  }

  .pdf-view {
    &-canvas {
      padding-top: 20px;
      display: flex;
      justify-content: center;
      background-color: #ededed;

      canvas {
        margin-bottom: 10px;
        width: 794px;
        height: 1123px;
      }
    }
  }
</style>
